﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FineUI;
using ZHDJ.Core.Caching;
using ZHDJ.Data.Models.Org;
using ZHDJ.Data.Models.Forum;

namespace ZHDJ.WebPage
{
    public class TreeControlBusiness
    {
        private MemoryCacheManager Cache;
        /// <summary>
        /// 缓存键
        /// </summary>
        public string CacheKey { get; set; }

        /// <summary>
        /// 缓存键
        /// </summary>
        public bool IsCache { get; set; }
        /// <summary>
        /// 节点ID字段 
        /// </summary>
        public string IdField { get; set; }

        /// <summary>
        /// 节点父ID字段 
        /// </summary>
        public string ParentField { get; set; }
        /// <summary>
        /// 节点显示文本字段 
        /// </summary>
        public string TextField { get; set; }

        public int Level = 0;
        /// <summary>
        /// 是否启用复选框
        /// </summary>
        public bool IsAllCheckBox { get; set; }

        /// <summary>
        /// 是否启用树叶复选框
        /// </summary>
        public bool IsLeafCheckBox { get; set; }

        /// <summary>
        /// 是否启用复选框事件
        /// </summary>
        public bool EnableCheckEvent { get; set; }

        public string OnClientClick { get; set; }

        /// <summary>
        /// 图标
        /// </summary>
        public string IconUrl  { get; set; }

       
        /// <summary>
        /// 图标
        /// </summary>
        public string NavigateUrl { get; set; }

        public string Target { get; set; }

        public TreeNode Node { get; set; }

        public string CommandName { get; set; }

        /// <summary>
        /// 是否启用点击事件
        /// </summary>
        public bool EnableClickEvent = false;

        public TreeControlBusiness(string idField, string parentField, string textField, bool isCache = true, string cacheKey = "")
        {
            Cache = new MemoryCacheManager();
            IdField = idField;
            ParentField = parentField;
            TextField = textField;
            IsCache = isCache;
            CacheKey = string.IsNullOrEmpty(cacheKey) ? string.Format("{0}_{1}_{2}", idField, parentField, textField) : cacheKey;
            IsAllCheckBox = false;
            EnableCheckEvent = false;
            IsLeafCheckBox = false;
            Node = new TreeNode();
        }

        /// <summary>
        /// 绑定组织
        /// </summary>
        /// <param name="tree"></param>
        public void BindTreeBranch(Tree tree)
        {
            var nodes = new List<TreeNode>();
            if (IsCache)
            {
                var ds = Cache.Get<DataSet>(CacheKeys.Cache_Branch_All, () => PartyOrgBranch.GetBranchAll());
                nodes = Cache.Get<List<TreeNode>>(CacheKey, () => CreateTreeNodes(ds));
            }
            else
            {
                var ds = PartyOrgBranch.GetBranchAll();
                nodes = CreateTreeNodes(ds);
            }
            tree.Nodes.Clear();
            nodes.ForEach(a =>
            {
                tree.Nodes.Add(a);
            });    
        }

        public void BindTreeCameraBranch(Tree tree)
        {
            var nodes = new List<TreeNode>();
            if (IsCache)
            {
                var ds = Cache.Get<DataSet>(CacheKeys.Cache_Camera_Branch_All, () => PartyOrgBranch.GetCameraBranchAll());
                nodes = Cache.Get<List<TreeNode>>(CacheKey, () => CreateTreeNodes(ds));
            }
            else
            {
                var ds = PartyOrgBranch.GetCameraBranchAll();
                nodes = CreateTreeNodes(ds);
            }
            tree.Nodes.Clear();
            nodes.ForEach(a =>
            {
                tree.Nodes.Add(a);
            });

        }

        public void BindTreeCameraBranch(Tree tree,string branchid)
        {
            var nodes = new List<TreeNode>();
            if (IsCache)
            {
                var ds = Cache.Get<DataSet>(CacheKeys.Cache_Camera_Branch_All, () => PartyOrgBranch.GetCameraBranchAll());
                //nodes = Cache.Get<List<TreeNode>>(CacheKey, () => CreateTreeNodes(ds,branchid));
                nodes = CreateTreeNodes(ds, branchid);
            }
            else
            {
                var ds = PartyOrgBranch.GetCameraBranchAll();
                nodes = CreateTreeNodes(ds,branchid);
            }
            tree.Nodes.Clear();
            nodes.ForEach(a =>
            {
                tree.Nodes.Add(a);
            });

        }

        /// <summary>
        /// 绑定版块
        /// </summary>
        /// <param name="tree"></param>
        public void BindTreeForumType(Tree tree)
        {
            var ds = PartyForumType.GetForumTypeAll();
            
            var nodes = CreateTreeNodes(ds);
            var root  = new TreeNode
            {
                CommandArgument = "",
                Text = "所有版块",
                Expanded = true,
                NodeID = "root",
                EnableClickEvent = EnableClickEvent,
                EnableCheckBox = IsAllCheckBox,
                EnableCheckEvent = EnableCheckEvent,
                OnClientClick = string.IsNullOrEmpty(OnClientClick) ? "" : OnClientClick.Replace("$nodeid", "root")
            };
            if (!string.IsNullOrEmpty(IconUrl))
            {
                root.IconUrl = IconUrl;
            }
            nodes.ForEach(a =>
            {
                root.Nodes.Add(a);
            });
            tree.Nodes.Clear();
            tree.Nodes.Add(root);
        }

        #region 
        /// <summary>
        /// 创建树节点TreeNode
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public List<TreeNode> CreateTreeNodes(DataSet ds)
        {
            var nodes = new List<TreeNode>();

            if (!ds.Relations.Contains("TreeRelation"))
            {
                ds.Relations.Add("TreeRelation", ds.Tables[0].Columns[IdField], ds.Tables[0].Columns[ParentField], false);
            }
            
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                TreeNode node = new TreeNode();
                if (ParentField != null && row[ParentField] != "") continue;
                Level = 1;
                node = new TreeNode
                {
                    CommandArgument = "",
                    Text = row[TextField].ToString(),
                    Expanded = true,
                    NodeID = row[IdField].ToString(),
                    EnableClickEvent = EnableClickEvent,
                    EnableCheckBox = IsAllCheckBox,
                    EnableCheckEvent = EnableCheckEvent,
                    OnClientClick = string.IsNullOrEmpty(OnClientClick) ? "" : OnClientClick.Replace("$nodeid", row[IdField].ToString()),
                    NavigateUrl = string.IsNullOrEmpty(NavigateUrl) ? "" : NavigateUrl.Replace("$nodeid", row[IdField].ToString()),
                    Target = string.IsNullOrEmpty(Target) ? "_self" : Target,
                };
                if (!string.IsNullOrEmpty(IconUrl))
                {
                    node.IconUrl = IconUrl;
                }
                nodes.Add(node);
                ResolveSubTreeNodes(row, node);
            }
            return nodes;
        }

        public List<TreeNode> CreateTreeNodes(DataSet ds,string branchid)
        {
            var nodes = new List<TreeNode>();

            if (!ds.Relations.Contains("TreeRelation"))
            {
                ds.Relations.Add("TreeRelation", ds.Tables[0].Columns[IdField], ds.Tables[0].Columns[ParentField], false);
            }

            var rootnode = ds.Tables[0].Select("BranchID = '" + branchid + "'").FirstOrDefault();
            if (rootnode != null) {
                var node = new TreeNode
                {
                    CommandArgument = "",
                    Text = rootnode[TextField].ToString(),
                    Expanded = true,
                    NodeID = rootnode[IdField].ToString(),
                    EnableClickEvent = EnableClickEvent,
                    EnableCheckBox = IsAllCheckBox,
                    EnableCheckEvent = EnableCheckEvent,
                    OnClientClick = string.IsNullOrEmpty(OnClientClick) ? "" : OnClientClick.Replace("$nodeid", rootnode[IdField].ToString()),
                    NavigateUrl = string.IsNullOrEmpty(NavigateUrl) ? "" : NavigateUrl.Replace("$nodeid", rootnode[IdField].ToString()),
                    Target = string.IsNullOrEmpty(Target) ? "_self" : Target,
                };
                if (!string.IsNullOrEmpty(IconUrl))
                {
                    node.IconUrl = IconUrl;
                }
                nodes.Add(node);
                ResolveSubTreeNodes(rootnode, node);
            }
            return nodes;
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="dataRow"></param>
        /// <param name="treeNode"></param>
        private void ResolveSubTreeNodes(DataRow dataRow, TreeNode treeNode)
        {
            DataRow[] rows = dataRow.GetChildRows("TreeRelation");
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    var node = new TreeNode
                    {
                        CommandArgument = treeNode.NodeID,
                        Expanded = false,
                        Text = row[TextField].ToString(),
                        NodeID = row[IdField].ToString(),
                        EnableClickEvent = EnableClickEvent,
                        EnableCheckBox = IsAllCheckBox,
                        EnableCheckEvent = EnableCheckEvent,
                        OnClientClick = string.IsNullOrEmpty(OnClientClick) ? "" : OnClientClick.Replace("$nodeid", row[IdField].ToString()),
                        NavigateUrl = string.IsNullOrEmpty(NavigateUrl) ? "" : NavigateUrl.Replace("$nodeid", row[IdField].ToString()),
                        Target = string.IsNullOrEmpty(Target) ? "_self" : Target,
                        CommandName = string.IsNullOrEmpty(CommandName) ? "" : row[CommandName].ToString()
                    };
                    if (!string.IsNullOrEmpty(IconUrl))
                    {
                        node.IconUrl = IconUrl;
                    }
                    treeNode.Nodes.Add(node);
                    ResolveSubTreeNodes(row, node);
                }
            }
            else
            {
                if (IsLeafCheckBox)
                {
                    treeNode.EnableCheckBox = true;
                    treeNode.EnableCheckEvent = EnableCheckEvent;
                }
            }
        }
        #endregion
    }
}
